package com.dzz.sjgl.service.impl;

import com.dzz.sjgl.entity.UserInfo;
import com.dzz.sjgl.jpa.UserRepository;
import com.dzz.sjgl.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;


/**
 * @author KRIC
 * @ClassName UserServiceImpl
 * @Date: 2018-8-1 17:25
 * @Description:
 */
@Service
public class UserServiceImpl implements IUserService {
    private final UserRepository userRepository;

    @Autowired
    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }


    /**
     * 通过email查询用户
     */
    @Override
    public UserInfo getUserByLogin(String login) {
        return userRepository.getUserByLogin(login);
    }

    /**
     * 通过id查询用户
     */
    @Override
    public UserInfo getUserById(int id) {
        return userRepository.getOne(id);
    }

    /**
     * 保存更新
     */
    @Override
    public UserInfo save(UserInfo userInfo) {
        return userRepository.save(userInfo);
    }


    /**
     * 分页
     */
    @Override
    public Page<UserInfo> findAll(Integer pageNumber, Integer pageSize) {
        Sort sort = new Sort(Sort.Direction.DESC, "lastLogin");
        Pageable pageable = PageRequest.of(pageNumber - 1, pageSize, sort);
        return userRepository.findAll(pageable);
    }

    /**
     * 分页
     */
    @Override
    public Page<UserInfo> findAllByQuery(Integer pageNumber, Integer pageSize, final String name, final String login) {
        Sort sort = new Sort(Sort.Direction.DESC, "lastLogin");
        Pageable pageable = PageRequest.of(pageNumber - 1, pageSize, sort);
        return userRepository.findAll((Specification<UserInfo>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicateList = new ArrayList<>();
            if (!StringUtils.isEmpty(name)) {
                predicateList.add(criteriaBuilder.like(root.get("name").as(String.class), "%" + name.trim() + "%"));
            }
            if (!StringUtils.isEmpty(login)) {
                predicateList.add(criteriaBuilder.like(root.get("login").as(String.class), "%" + login.trim() + "%"));
            }
            return criteriaBuilder.and(predicateList.toArray(new Predicate[0]));
        }, pageable);
    }


}
